import React, { useRef } from 'react';
import { useDrag, useDrop } from 'react-dnd';
import update from 'immutability-helper';
import DragAndDropHOC from './DragAndDropHOC';
import config from '@/pages/WeChatModule/WechatPage/components/Drawer/components/components.config'
import './index.less';

const DndDragContext = (props) => {
  const { data = [], accept, onEnd, layout = 'horizontal', children } = props;
  // 移动数据处理
  const moveRow = (dragIndex, hoverIndex, item) => {
    const { dataIndex } = item
    if (dataIndex) {
      const movefile = []
      data.forEach((val, index) => {
        if (index !== hoverIndex) {
          movefile.push(val)
        }
        else {
          movefile.push(val)
          movefile.push(config[dataIndex])
        }
      })
      onEnd(movefile);
    }
    else {
      const dragRow = data[dragIndex];
      const movefile = update(data, {
        $splice: [
          [dragIndex, 1],
          [hoverIndex, 0, dragRow],
        ],
      });
      onEnd(movefile);
    }

  };

  // 拖动项目
  const DragableListItem = ({ originNode, index }) => {
    const ref = useRef();
    // accept 拖拽对象落点的属性 区分拖拽对象的不同落点区域 与useDrag type对应
    const [{ isOver, dropClassName }, drop] = useDrop({
      accept: ['label', 'swiper', 'navigation', 'search'],
      collect: (monitor) => {
        const { index: dragIndex } = monitor.getItem() || {};
        if (dragIndex === index) {
          return {};
        }
        return {
          isOver: monitor.isOver(),
          dropClassName: dragIndex < index ? ' drop-over-downward' : ' drop-over-upward',
        };
      },
      drop: (item) => moveRow(item.index, index, item),
    });
    // type 拖拽对象落点的属性 区分拖拽对象的不同落点区域 与useDrop accept对应
    const [, drag] = useDrag({
      item: { type: 'label', index },
      collect: (monitor) => ({
        isDragging: monitor.isDragging(),
      }),
    });
    drop(drag(ref));
    return (
      <div
        ref={ref}
        className={`dakale-draggable-list-item ${isOver ? dropClassName : ''}`}
        style={{ cursor: 'move' }}
      >
        {originNode}
      </div>
    );
  };

  return (
    <div
      className="dakale-move-dom-wrapper"
      style={{ flexDirection: { horizontal: 'row', vertical: 'column' }[layout] }}
    >
      {children.map((item, index) => (
        <DragableListItem
          key={`domDnd${index}`}
          originNode={item}
          index={index}
        ></DragableListItem>
      ))}
    </div>

  );
};

export default DndDragContext;
